package com.fbooks.Controller;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPObject;
import com.fasterxml.jackson.annotation.JsonAlias;
import com.fbooks.bean.Email;
import com.fbooks.bean.User;
import com.fbooks.service.UserService;
import com.fbooks.utils.email.Impl.AccountEmailException;
import com.fbooks.utils.fastdfsUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: LuoRunFeng
 * @e-mail: 475403147@qq.com
 * @Time: 2020/4/16 20:30
 * @Version 1.0
 */
@Controller
@CrossOrigin
public class UserController {
    @Autowired
    private UserService userService;

    @Resource
    private HttpServletRequest httpServletRequest;



    @RequestMapping("{uid}")
    @ResponseBody
    public User selectUserInfoById(@PathVariable String uid){
        User userInfoById = userService.selectUserInfoById(uid);
        return userInfoById;
    }



    /**
     * 获取所有用户信息
     * @return
     */
    @RequestMapping("getAllUser")
    @ResponseBody
    public PageInfo<User> getAllUserList(@RequestBody JSONObject jsonObject){
        //获取川谷来的数据
        Integer pages =  Integer.valueOf(jsonObject.getString("pages"));
        Integer pageNum = Integer.valueOf(jsonObject.getString("pageNum"));
        PageHelper.startPage(pages,pageNum);

        List<JSONObject> jsonObjectList = new ArrayList<>();

        List<User> userList = userService.getAllUser();

        /**
         * 封装只需要的信息
         */
        for (User user : userList) {
            user.setPassword("null");
            user.setToken("null");
        }
        PageInfo<User> pageInfo = new PageInfo<>(userList);

        return pageInfo;
    }


    /**
     * 用户登陆
     * @param jsonObject
     * @return
     */
    @RequestMapping("login")
    @ResponseBody
    public JSONObject userLogin(@RequestBody JSONObject jsonObject){
        String email = (String) jsonObject.get("email");
        String password = (String) jsonObject.get("password");

        JSONObject userInfo = userService.getUserInfo(email,password);
        return userInfo;
    }

    /**
     *用户注册
     * @return
     */
    @RequestMapping("register")
    @ResponseBody
    public JSONObject insertUserInfo(@RequestBody JSONObject jsonObject){
        String email = (String) jsonObject.get("email");
        String password = (String) jsonObject.get("password");
        String ip = (String) jsonObject.get("ip");

        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        user.setIp(ip);
        user.setSex("男");
        user.setWorkAddress("无");
        user.setFamilyAddress("无");
        user.setPersonIntro("无");
        JSONObject registerInfo=userService.saveUserInfo(user);
        return registerInfo;
    }


    /**
     * 获取用户中心数据
     * @return
     */
    @RequestMapping("getUserInfo")
    @ResponseBody
    public JSONObject getUserInfo(){
        //获取请求头token
        String token = httpServletRequest.getHeader("Authorization");
        JSONObject userInfo = userService.getUserInfo(token);
        return userInfo;
    }

    /**
     * 用户信息修改
     * @param json
     * @return
     */
    @RequestMapping("modifiy")
    @ResponseBody
    public JSONObject updateUserInfo(@RequestBody JSONObject  json){

        User user = new User();

        user.setFamilyAddress(String.valueOf(json.get("familyAddress")));
        user.setUsername(String.valueOf(json.get("username")));
        user.setSex(String.valueOf(json.get("sex")));
        user.setPersonIntro(String.valueOf(json.get("personIntro")));
        user.setWorkAddress(String.valueOf(json.get("workAddress")));
        user.setEmail(String.valueOf(json.get("email")));

        //用户修改信息传不传密码
        if (String.valueOf(json.get("password")) != "null"){
            user.setPassword(String.valueOf(json.get("password")));
            System.out.println("设置密码");
        }

        //获取请求头token
        String token = httpServletRequest.getHeader("Authorization");
        //获取用户信息
        JSONObject userInfo = userService.getUserInfo(token);
        //判断token 是否过期，或者token 错误
        if ((boolean)userInfo.get("isSuccess")){

            //这里传来的数据没有id，没有标识符
            //获取用户id
            String uid = (String) userInfo.get("uid");
            user.setId(uid);

            //判断是否更新成功
            JSONObject jsonObject = userService.updateUserInfo(user);
            if ((boolean)jsonObject.get("isSuccess")){
                //成功更新
                //获取用户信息
                User user1 = userService.getUserInfoById(uid);
                jsonObject.put("User", user1);
            }
            return jsonObject;
        }else{
            return userInfo;
        }
    }



    @RequestMapping("updateAvatar")
    @ResponseBody
    public JSONObject updateAvatar(@RequestBody User user){
        JSONObject jsonObject = new JSONObject();
        //获取请求头token
        String token = httpServletRequest.getHeader("Authorization");
        //获取用户信息
        JSONObject userInfo = userService.getUserInfo(token);
        //判断token 是否过期，或者token 错误
        if ((boolean)userInfo.get("isSuccess")){
            //这里传来的数据没有id，没有标识符
            //获取用户id
            String uid = (String) userInfo.get("uid");
            user.setId(uid);

            //判断是否更新成功
            userService.updateAvatar(user);
            jsonObject.put("isSuccess", true);
            return jsonObject;
        }else{
            return userInfo;
        }
    }




    /**
     * 用户信息删除
     * @param id
     * @return
     */
    @RequestMapping("delete")
    @ResponseBody
    public JSONObject deleteUserInfo(String id){
        JSONObject jsonObject = userService.deleteUserInfo(id);
        return jsonObject;
    }



    /**
     * 图片上传
     * @param picture
     * @return
     */
    @RequestMapping("fileUpload")
    @ResponseBody
    public JSONObject fileUpload(@RequestParam("picture") MultipartFile picture){

        System.out.println(picture);
        //将图片村粗到文件系统中
        String imgUrl= fastdfsUtils.uploadImage(picture);
        System.out.println(imgUrl);
        JSONObject backInfo = new JSONObject();
        backInfo.put("imgUrl", imgUrl);
        return backInfo;
    }


    /**
     * 发送邮件验证码
     * @param email
     * @return
     * @throws AccountEmailException
     */
    @RequestMapping("/sendEmail")
    @ResponseBody
    public JSONObject sendEmail(@RequestBody Email email) throws AccountEmailException {

        //首先需要判断账号是否存在
        if (userService.getUserInfoByEmail(email.getAddressee())){
            try{
                JSONObject backInfoJson = userService.sendEmail(email.getAddressee());
                //  将邮件地址一并返回
                backInfoJson.put("email", email.getAddressee());
                return backInfoJson;
            }catch (Exception e) {
                throw new AccountEmailException("邮件发送失败", e);
            }
        }else {
            //不存在
            JSONObject backInfo = new JSONObject();
            backInfo.put("isSuccess", false);
            return backInfo;
        }
    }


    /**
     * 更新密码
     * @param user
     * @return
     */
    @RequestMapping("/updatePassword")
    @ResponseBody
    public JSONObject updatePassword(@RequestBody User user){

        System.out.println(user);
        JSONObject backInfo = userService.updatePassword(user);
        return backInfo;
    }

    @RequestMapping("/loginStatus")
    @ResponseBody
    public boolean jugeLoginStatus(){
        //获取请求头token
        String token = httpServletRequest.getHeader("Authorization");

        User user = userService.getUserInfoByToken(token);
        if (user != null){
            if (token.equals(user.getToken())){
                return true;
            }
        }
        return false;
    }

    @RequestMapping("/getInfoById")
    @ResponseBody
    public JSONObject getUserInfoById(@RequestBody User user){
        User userInfoById = userService.getUserInfoById(user.getId());
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("avatar",userInfoById.getAvatar());
        jsonObject.put("username",userInfoById.getUsername());
        jsonObject.put("personIntro",userInfoById.getPersonIntro());

        return jsonObject;
    }

    @RequestMapping("/deleteUser")
    @ResponseBody
    public void deleteUser(@RequestBody JSONObject idObject){
        String id = String.valueOf(idObject.get("id"));
        userService.deleteUser(id);
    }

}
